﻿using System.Runtime.InteropServices;
using System.Text;

namespace Goway.IniConifigHelper
{
    /// <summary>
    /// ini配置文件读写
    /// </summary>
    public class IniFileReadWite
    {
        private readonly string _strPath;

        /// <summary>
        /// INI文件路径
        /// </summary>
        public string StrPath
        {
            get { return _strPath; }
            //set { _strPath = value; }
        }

        [DllImport("kernel32")]
        private static extern long WritePrivateProfileString(string section, string key, string val, string filePath);
        [DllImport("kernel32")]
        private static extern int GetPrivateProfileString(string section, string key, string def, StringBuilder retVal, int size, string filePath);

        /// <summary>
        /// 构造函数
        /// </summary>
        /// <PARAM name="INIPath">INI文件路径</PARAM>
        public IniFileReadWite(string strPath)
        {
            _strPath = strPath;
        }

        /// <summary>
        /// 写入ini数据
        /// </summary>
        /// <PARAM name="Section">项目名称</PARAM>
        /// <PARAM name="Key">分项名称</PARAM>
        /// <PARAM name="Value">分项值</PARAM>
        public void WriteIniValue(string section, string key, string value)
        {
            WritePrivateProfileString(section, key, value, StrPath);
        }

        /// <summary>
        /// 读出ini数据
        /// </summary>
        /// <PARAM name="Section">项目名称</PARAM>
        /// <PARAM name="Key">分项名称</PARAM>
        /// <returns>分项值</returns>
        public string ReadIniValue(string section, string key)
        {
            StringBuilder temp = new StringBuilder(255);
            int i = GetPrivateProfileString(section, key, "", temp, 255, StrPath);
            return temp.ToString();
        }
    }
}